package com.example.coroutines_test.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.coroutines_test.api.ApiService
import com.example.coroutines_test.data.Message
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MessageViewModel : ViewModel() {

    private val Tag = "MessageViewModel"
    private val _messages = MutableLiveData<List<Message>>()
    val messages: LiveData<List<Message>> get() = _messages

    private val _progress = MutableLiveData(0)
    val progress: LiveData<Int> = _progress

    init {
        fetchUser()
    }

    public fun fetchUser() {

        val progressJob = viewModelScope.launch {
            _progress.value = 0
            while (isActive) {
                delay(500)
                _progress.value = _progress.value!!.toInt() + 10


                if (_progress.value == 90) {
                    break
                }
            }
        }

        //val coroutineScope = CoroutineScope(Dispatchers.IO)
        // 需要引入 lifecycle-viewmodel = { group = "androidx.lifecycle",name="lifecycle-viewmodel-ktx" ,version= "2.8.7"} 依赖
        // 才能使用 viewModelScope
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val retrofit = Retrofit.Builder()
                    .baseUrl("https://jsonplaceholder.typicode.com")
                    //.baseUrl("http://192.168.1.140:8080/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                val apiService = retrofit.create(ApiService::class.java)
                val messages = apiService.getUserById()  // 异步调用

                delay(1000)

                progressJob.cancel()


                /*withContext(Dispatchers.Main) {
                    _progress.value = 100
                    _messages.value = messages.body()
                }*/

                // postValue() 专门用于异步
                _progress.postValue( 100)
                _messages.postValue(messages.body())

            } catch (e: Exception) {
                // 处理异常
                Log.e(Tag, e.message.toString())
            }
        }

    }
}